package com.ganmiao.server.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ganmiao.resp.PageResult;
import com.ganmiao.server.sys.entity.SysUserRole;
import com.ganmiao.server.sys.mapper.SysUserRoleMapper;
import com.ganmiao.server.sys.query.SysUserRoleQuery;
import com.ganmiao.server.sys.repository.SysUserRoleRepository;
import com.ganmiao.server.sys.vo.SysUserRoleVo;
import com.ganmiao.server.sys.vo.SysUserVo;
import com.ganmiao.server.user.context.UserAuthContext;
import com.ganmiao.utils.PageListUtil;
import com.ganmiao.utils.StatusUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色信息
 */
@Service
public class SysUserRoleService {

    //用户角色信息
    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;

    //用户角色信息
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 新增用户角色信息 (关联用户)
     *
     * @param sysUserRole
     * @return
     */
    public boolean addSysUserRole(SysUserRole sysUserRole) {

        return sysUserRoleMapper.addSysUserRole(sysUserRole);

    }

    /**
     * 新增用户角色信息 (用户关联角色)
     *
     * @param userId
     * @param roleIds
     * @return
     */
    public boolean addSysUserRoleByUserId(Integer userId, List<Integer> roleIds) {

        //用户角色信息数据
        List<SysUserRole> list = new ArrayList<>();

        //用户角色信息数据赋值
        roleIds.forEach(item -> {

            SysUserRole sysUserRole = SysUserRole.builder()
                    .userId(userId)
                    .roleId(item)
                    .build();
            list.add(sysUserRole);

        });

        if (!list.isEmpty()) {
            return sysUserRoleMapper.addSysUserRoleByUserId(list);
        }

        return true;

    }

    /**
     * 删除用户角色信息 (取消授权)
     *
     * @param sysUserRole
     * @return
     */
    public boolean deleteSysUserRole(SysUserRole sysUserRole) {

        //删除条件
        LambdaUpdateWrapper<SysUserRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUserRole::getRoleId, sysUserRole.getRoleId())
                .eq(SysUserRole::getUserId, sysUserRole.getUserId())
                .set(SysUserRole::getStatus, StatusUtils.FAILURE);
        return sysUserRoleRepository.update(updateWrapper);

    }

    /**
     * 删除用户角色信息 (用户关联角色)
     *
     * @param userId
     * @return
     */
    public boolean deleteSysUserRoleByUserId(Integer userId) {

        //删除条件
        LambdaUpdateWrapper<SysUserRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUserRole::getUserId, userId)
                .set(SysUserRole::getStatus, StatusUtils.FAILURE);
        return sysUserRoleRepository.update(updateWrapper);

    }

    /**
     * 修改用户角色信息 (用户关联角色)
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Transactional
    public boolean updateSysUserRoleByUserId(Integer userId, List<Integer> roleIds) {

        //删除用户角色信息
        deleteSysUserRoleByUserId(userId);

        //新增用户角色信息
        boolean addedSysUserRoleByUserId = addSysUserRoleByUserId(userId, roleIds);

        return addedSysUserRoleByUserId;

    }

    /**
     * 获取用户角色信息 (关联用户/取消授权)
     *
     * @param sysUserRoleQuery
     * @return
     */
    public PageResult<SysUserRoleVo> getSysUserRoleList(SysUserRoleQuery sysUserRoleQuery) {

        //获取系统编码并赋值
        String sysCode = UserAuthContext.getSysCode();
        sysUserRoleQuery.setSysCode(sysCode);
        SysUserVo loginUser = UserAuthContext.getLoginUser();
        if (loginUser != null && loginUser.getSupplierId() != null) {
            sysUserRoleQuery.setSupplierId(loginUser.getSupplierId());
        }
        if (loginUser != null && loginUser.getShopId() != null) {
            sysUserRoleQuery.setShopId(loginUser.getShopId());
        }
        if (StringUtils.isBlank(sysUserRoleQuery.getUserName())) {
            sysUserRoleQuery.setUserName(null);
        }

        //分页对象
        IPage<SysUserRoleVo> iPage = new Page<>(sysUserRoleQuery.getPage(), sysUserRoleQuery.getPageSize());

        //验证查询是已关联还是未关联
        if ("exist".equals(sysUserRoleQuery.getSelectType())) {

            //获取已关联用户信息
            IPage<SysUserRoleVo> sysUserRoleListExist = sysUserRoleMapper.getSysUserRoleListExist(iPage, sysUserRoleQuery);
            return PageListUtil.getPageResult(sysUserRoleListExist);

        }

        //获取未关联用户信息
        IPage<SysUserRoleVo> sysUserRoleListNotExist = sysUserRoleMapper.getSysUserRoleListNotExist(iPage, sysUserRoleQuery);

        return PageListUtil.getPageResult(sysUserRoleListNotExist);

    }

    /**
     * 获取用户角色ID集合
     *
     * @param userId
     * @return
     */
    List<Integer> getSysUserRoleByUserId(Integer userId) {

        //查询条件
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId)
                .eq(SysUserRole::getStatus, StatusUtils.PASS);

        return sysUserRoleRepository.list(queryWrapper).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

    }

}
